package com.shootforthestars.util;

import java.util.Map;
import java.util.TreeMap;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

/**
 * The ImageManager class provides lazy initialization for Image loading.
 * 
 * @author jmcomets
 */
public final class ImageManager {
	/**
	 * Singleton boilerplate: class instance.
	 */
	private static ImageManager instance = null;
	
	/**
	 * Relative path to image directory.
	 */
	private static final String IMAGE_DIRECTORY = "assets/images";

	/**
	 * Mapping from filename to image object.
	 */
	private Map<String, Image> images;

	/**
	 * Singleton boilerplate: private constructor.
	 */
	private ImageManager() {
		images = new TreeMap<String, Image>();
	}

	/**
	 * Singleton boilerplate: class access to instance.
	 * 
	 * @return the image manager's instance
	 */
	private final static ImageManager getInstance() {
		if (instance == null) {
			instance = new ImageManager();
		}
		return instance;
	}

	/**
	 * Lazy-load an image.
	 * 
	 * @param filename
	 * @return the loaded image or null
	 */
	public static Image getImage(String filename) {
		try {
			return loadImage(filename);
		} catch (SlickException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Lazy-load an image.
	 * 
	 * @param filename
	 * @return the loaded image
	 * @throws SlickException
	 */
	public static Image loadImage(String filename) throws SlickException {
		ImageManager im = getInstance();
		Image image = im.images.get(filename);
		if (image == null) {
			image = new Image(IMAGE_DIRECTORY + "/" + filename);
			im.images.put(filename, image);
		}
		return image;
	}
}
